package com.recyclerviewdemo.Fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.recyclerviewdemo.R;
import com.recyclerviewdemo.Services.GankApi;
import com.recyclerviewdemo.Services.GankUrl;
import com.recyclerviewdemo.Services.NetWork;
import com.recyclerviewdemo.adapters.AndroidAdapter;
import com.recyclerviewdemo.adapters.RecyclerviewAdapter;
import com.recyclerviewdemo.entity.GankResult;

import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * Created by Yang on 2016/9/5.
 */
public class AndroidFragment extends Fragment {

    private View mRootView;

    private RecyclerView recycler_view;
    private SwipeRefreshLayout swipe;
    private int contentQuantity = 20;
    private AndroidAdapter mAdapter;
    private List<GankResult.ResultsBean> mData;
    private boolean mIsFirstTimeTouchBottom = true;
    private RecyclerView.LayoutManager layoutManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.fragment_android, container, false);
        }
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }

        initView();
        initData();

        return mRootView;
    }

    private void initView(){
        recycler_view = (RecyclerView)mRootView.findViewById(R.id.android_recycler_view);
        swipe = (SwipeRefreshLayout)mRootView.findViewById(R.id.android_swipe);
    }

    private void initData(){
        layoutManager = new LinearLayoutManager(getActivity());
        mAdapter = new AndroidAdapter(getActivity());
        recycler_view.setAdapter(mAdapter);
        recycler_view.setLayoutManager(layoutManager);
        recycler_view.addOnScrollListener(getOnBottomListener(layoutManager));

        getNetData(false); //刚进入界面先刷新一次

        //刷新时执行的事件
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData(true);
            }
        });
    }


    private void getNetData(boolean isLoadMore){
        swipe.measure(View.MEASURED_SIZE_MASK, View.MEASURED_HEIGHT_STATE_SHIFT);
        swipe.setRefreshing(true);

        if (isLoadMore) contentQuantity = contentQuantity + 10;
        Observable.combineLatest(NetWork.getGankApi().getAllDate(GankUrl.FLAG_GIRLS, contentQuantity, 1), NetWork.getGankApi().getAllDate(GankUrl.FLAG_Android, contentQuantity, 1),
                new Func2<GankResult, GankResult, Void>() {
                    @Override
                    public Void call(GankResult PicResult, GankResult androidData) {
                        mData = androidData.getResults();
                        mAdapter.setPicData(PicResult.getResults());
                        mAdapter.setAndroidData(androidData.getResults());
                        return null;
                    }
                })

                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Void>() {
                    @Override
                    public void onCompleted() {
                        swipe.setRefreshing(false);
                        //Log.e("oncomplete","sssss");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
                        swipe.setRefreshing(false);
                    }

                    @Override
                    public void onNext(Void aVoid) {
                        mAdapter.notifyDataSetChanged();
                        //Log.e("oncomplete", ""+mData.size() );
                    }
                });
    }

    RecyclerView.OnScrollListener getOnBottomListener(final RecyclerView.LayoutManager layoutManager) {
        return new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItem = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                int totalItemCount = layoutManager.getItemCount();
                //lastVisibleItem >= totalItemCount - 4 表示剩下4个item自动加载，各位自由选择
                // dy>0 表示向下滑动
                if (!swipe.isRefreshing() && lastVisibleItem >= totalItemCount - 2 && dy > 0) {
                    if (!mIsFirstTimeTouchBottom) {
                        swipe.setRefreshing(true);
                        getNetData(true);
                    } else {
                        mIsFirstTimeTouchBottom = false;
                    }
                }
            }
        };
    }
}
